#!/usr/bin/env python3
"""
Debug script to identify issues with routing chain integration
"""

from app.services.lcel_routing_service import LCELRoutingService
from app.services.chat_service_simple import ChatServiceSimple
from app.core.config import settings
from langchain_openai import ChatOpenAI
import traceback


def debug_routing_chain_issue():
    """Debug the specific issue with routing chain in agent"""
    print("🔍 调试Agent路由链问题")
    print("=" * 50)

    # Initialize services
    lcel_service = LCELRoutingService()
    chat_service = ChatServiceSimple()

    # Test the exact scenario that's failing
    query = "我想知道1995年的生肖"
    conversation_history = []  # Empty history for first test

    try:
        # Test 1: Check if basic routing chain works
        print("\n📝 测试 1: 基本路由链功能")
        routing_chain = lcel_service.create_routing_branch_lcel()
        result = routing_chain.invoke(query)
        print(f"✅ 基本路由链成功: {result[:100]}...")

    except Exception as e:
        print(f"❌ 基本路由链失败: {e}")
        traceback.print_exc()

    try:
        # Test 2: Check if memory-aware routing chain works
        print("\n📝 测试 2: 记忆感知路由链功能")
        memory_chain = lcel_service.create_memory_aware_routing_branch_lcel()
        formatted_history = lcel_service._format_conversation_history([])

        result = memory_chain.invoke({
            "query": query,
            "conversation_history": formatted_history
        })
        print(f"✅ 记忆感知路由链成功: {result[:100]}...")

    except Exception as e:
        print(f"❌ 记忆感知路由链失败: {e}")
        traceback.print_exc()

    try:
        # Test 3: Check if smart routing processor works directly
        print("\n📝 测试 3: 智能路由处理器")

        def smart_routing_processor(context):
            user_query = context.get("query", "")
            tool_results = context.get("tool_results", {})
            conversation_history = context.get("conversation_history", [])

            if tool_results:
                return f"工具结果处理: {str(tool_results)}"
            else:
                if conversation_history:
                    routing_chain = lcel_service.create_memory_aware_routing_branch_lcel()
                    formatted_history = lcel_service._format_conversation_history(conversation_history)
                    return routing_chain.invoke({
                        "query": user_query,
                        "conversation_history": formatted_history
                    })
                else:
                    routing_chain = lcel_service.create_routing_branch_lcel()
                    return routing_chain.invoke(user_query)

        context = {
            "query": query,
            "tool_results": {},
            "conversation_history": conversation_history
        }

        result = smart_routing_processor(context)
        print(f"✅ 智能路由处理器成功: {result[:100]}...")

    except Exception as e:
        print(f"❌ 智能路由处理器失败: {e}")
        traceback.print_exc()

    try:
        # Test 4: Check if LLM integration works
        print("\n📝 测试 4: LLM集成")
        llm = ChatOpenAI(
            model="deepseek-chat",
            temperature=0.7,
            api_key=settings.openai_api_key,
            base_url=settings.openai_base_url
        )

        messages = [{"role": "user", "content": query}]
        response = llm.invoke(messages)
        print(f"✅ LLM调用成功: {response.content[:100]}...")

    except Exception as e:
        print(f"❌ LLM调用失败: {e}")
        traceback.print_exc()


def debug_agent_context():
    """Debug the context building in agent"""
    print("\n🔍 调试Agent上下文构建")
    print("=" * 50)

    try:
        from app.core.database import get_sync_db
        from app.services.chat_memory_service import ChatMemoryService

        # Test database connection and memory service
        print("\n📝 测试数据库连接")
        db = next(get_sync_db())
        print("✅ 数据库连接成功")
        db.close()

        # Test memory service
        print("\n📝 测试记忆服务")
        memory_service = ChatMemoryService()
        print("✅ 记忆服务初始化成功")

        # Test conversation history retrieval
        print("\n📝 测试对话历史获取")
        conversation_id = 1
        history = memory_service.get_conversation_history(conversation_id, limit=10)
        print(f"✅ 对话历史获取成功: {len(history)} 条消息")

    except Exception as e:
        print(f"❌ 上下文调试失败: {e}")
        traceback.print_exc()


if __name__ == "__main__":
    print("🚀 路由链问题调试")
    print("=" * 60)

    debug_routing_chain_issue()
    debug_agent_context()

    print("\n✅ 调试完成")